package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.service.CourseBaseInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 课程基本信息管理业务接口
 */
@Service
public class CourseBaseInfoServiceImpl  implements CourseBaseInfoService {

    @Autowired
    private CourseBaseMapper courseBaseMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    /**
     * 课程查询
     * @param pageParams
     * @param queryCourseParamsDto
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        // 1.拼接查询条件
        LambdaQueryWrapper<CourseBase> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        // 1.1.根据名称查询
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),
                CourseBase::getName,queryCourseParamsDto.getCourseName());
        // 1.2.根据审核状态查询
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),
                CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        // 1.3.根据发布状态查询
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),
                CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());
        // 1.4 机构id
        lambdaQueryWrapper.eq(CourseBase::getCompanyId,companyId);

        // 2.拼接分页条件
        Page<CourseBase> page=new Page<>(pageParams.getPageNo(),pageParams.getPageSize());

        // 3.查询
        Page<CourseBase> result = courseBaseMapper.selectPage(page, lambdaQueryWrapper);

        // 4.拼接返回结果
        PageResult<CourseBase> pageResult=new PageResult<>();
        pageResult.setItems(result.getRecords());
        pageResult.setCounts(result.getTotal());
        pageResult.setPage(pageParams.getPageNo());
        pageResult.setPageSize(pageParams.getPageSize());
        return pageResult;
    }

    /**
     * 添加课程
     * @param addCourseDto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId,AddCourseDto addCourseDto) {
        //条件校验
//        if(StringUtils.isBlank(addCourseDto.getName())){
//            throw new XueChengPlusException("课程名称不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getUsers())){
//            throw new XueChengPlusException("适用人群不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getMt())){
//            throw new XueChengPlusException("课程分类不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getSt())){
//            throw new XueChengPlusException("课程分类不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getGrade())){
//            throw new XueChengPlusException("课程等级不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getTeachmode())){
//            throw new XueChengPlusException("教学模式不能为空");
//        }
//        if(StringUtils.isBlank(addCourseDto.getCharge())){
//            throw new XueChengPlusException("收费规则不能为空");
//        }

        //保存CourseBase信息到数据库
        CourseBase courseBaseNew=new CourseBase();
        BeanUtils.copyProperties(addCourseDto,courseBaseNew);
        courseBaseNew.setCompanyId(companyId);
        courseBaseNew.setAuditStatus("202002");
        courseBaseNew.setStatus("203001");
        courseBaseNew.setCreateDate(LocalDateTime.now());
        int insert = courseBaseMapper.insert(courseBaseNew);
        if (insert<=0){
            throw new XueChengPlusException("新增课程失败");
        }

        //保存CourseMarket信息到数据库
        CourseMarket courseMarketNew=new CourseMarket();
        Long courseId = courseBaseNew.getId();
        BeanUtils.copyProperties(addCourseDto,courseMarketNew);
        courseMarketNew.setId(courseId);
        int i=saveCourseMarket(courseMarketNew);
        if (i<=0){
            throw new XueChengPlusException("保存课程营销信息失败");
        }

        //查询CourseBaseInfoDto信息并返回
        return getCourseBaseInfo(courseId);
    }

    public int saveCourseMarket(CourseMarket courseMarketNew){
        //校验数据
        String charge = courseMarketNew.getCharge();
        if (StringUtils.isBlank(charge)){
            throw new XueChengPlusException("请选择收费规则");
        }
        if (charge.equals("201001")){
            if (courseMarketNew.getPrice()==null||courseMarketNew.getPrice().floatValue()<0){
                throw new XueChengPlusException("课程为收费价格不能为空且必须大于0");
            }
        }

        //保存课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseMarketNew.getId());
        if (courseMarket==null){
            return courseMarketMapper.insert(courseMarketNew);
        }else{
            BeanUtils.copyProperties(courseMarketNew,courseMarket);
            courseMarket.setId(courseMarketNew.getId());
            return courseMarketMapper.updateById(courseMarket);
        }
    }


    /**
     * 根据id查询课程
     * @param courseId  课程id
     * @return
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        //根据id查询课程基本信息,并将其封装CourseBaseInfoDto对象
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase==null){
            return null;
        }
        CourseBaseInfoDto courseBaseInfoDto=new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);

        //根据id查询课程营销信息，并将其封装CourseBaseInfoDto对象
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if (courseMarket!=null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }

        //封装CourseBaseInfoDto的其他信息
        CourseCategory courseCategoryBySt = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategoryBySt.getName());
        CourseCategory courseCategoryByMt = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategoryByMt.getName());
        return courseBaseInfoDto;
    }


    @Transactional
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto) {

        //课程id
        Long courseId = dto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase==null){
            XueChengPlusException.cast("课程不存在");
        }

        //校验本机构只能修改本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        //封装基本信息的数据
        BeanUtils.copyProperties(dto,courseBase);
        courseBase.setChangeDate(LocalDateTime.now());

        //更新课程基本信息
        int i = courseBaseMapper.updateById(courseBase);

        //封装营销信息的数据
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarket);
        saveCourseMarket(courseMarket);
        //查询课程信息
        CourseBaseInfoDto courseBaseInfo = this.getCourseBaseInfo(courseId);
        return courseBaseInfo;

    }
}